<script setup lang="ts">
import { ref } from 'vue';
import { apiGet } from '@/request/apiUtils';
import { ElMessage } from 'element-plus';

// 初始化状态
const { value: state } = ref({
    loading: false,
    tableData: [] as TObj[],
    total: 0,
    pageSize: 10,
    currentPage: 1,
    queryData: {
        responsible_person: [],
        epic_name: undefined,
        story_name: undefined,
        fc_publish_version: [],
        task_type: undefined,
        plan_start_time_start: undefined,
        plan_start_time_end: undefined,
    },
    total_hours: 0  // 总工时
});

// 责任人选项
const responsiblePersonOptions = ref([] as string[]);
const filteredResponsiblePersonOptions = ref([] as string[]);

// 版本选项
const publishVersionOptions = ref([] as string[]);
const filteredPublishVersionOptions = ref([] as string[]);

// 任务类型选项
const taskTypeOptions = ref([] as string[]);

// 获取责任人列表
const fetchResponsiblePersons = async () => {
    try {
        const response: TObj = await apiGet('/tasks/responsible_persons');
        responsiblePersonOptions.value = response?.results || [];
        filteredResponsiblePersonOptions.value = response?.results || [];
    } catch (error) {
        console.error('Error fetching responsible persons:', error);
    }
};

// 获取版本列表
const fetchPublishVersions = async () => {
    try {
        const response: TObj = await apiGet('/tasks/publish_versions');
        publishVersionOptions.value = response?.results || [];
        filteredPublishVersionOptions.value = response?.results || [];
    } catch (error) {
        console.error('Error fetching publish versions:', error);
    }
};

// 获取任务类型列表
const fetchTaskTypes = async () => {
    try {
        const response: TObj = await apiGet('/tasks/task_types');
        taskTypeOptions.value = response?.results || [];
    } catch (error) {
        console.error('Error fetching task types:', error);
    }
};

// 责任人搜索过滤方法
const filterResponsiblePerson = (query: string) => {
    if (query) {
        filteredResponsiblePersonOptions.value = responsiblePersonOptions.value.filter(person =>
            person.toLowerCase().includes(query.toLowerCase())
        );
    } else {
        filteredResponsiblePersonOptions.value = [...responsiblePersonOptions.value];
    }
};

// 版本搜索过滤方法
const filterPublishVersion = (query: string) => {
    if (query) {
        filteredPublishVersionOptions.value = publishVersionOptions.value.filter(version =>
            version.toLowerCase().includes(query.toLowerCase())
        );
    } else {
        filteredPublishVersionOptions.value = [...publishVersionOptions.value];
    }
};

// 获取统计数据
const fetchData = async (page = state.currentPage, size = state.pageSize) => {
    state.loading = true;
    try {
        const apiUrl = '/tasks/human_resource_statistics';
        
        // 构建查询参数
        const params: TObj = {
            page,
            size
        };
        
        // 添加责任人筛选参数，支持多个责任人
        if (state.queryData.responsible_person) {
            if (Array.isArray(state.queryData.responsible_person)) {
                // 多个责任人，转换为逗号分隔的字符串
                params.responsible_person = state.queryData.responsible_person.join(',');
            } else {
                // 单个责任人，直接使用
                params.responsible_person = state.queryData.responsible_person;
            }
        }
        
        // 添加史诗筛选参数
        if (state.queryData.epic_name) {
            params.epic_name = state.queryData.epic_name;
        }
        
        // 添加故事筛选参数
        if (state.queryData.story_name) {
            params.story_name = state.queryData.story_name;
        }
        
        // 添加版本筛选参数，支持多个版本
        if (state.queryData.fc_publish_version) {
            if (Array.isArray(state.queryData.fc_publish_version)) {
                // 多个版本，转换为逗号分隔的字符串
                params.fc_publish_version = state.queryData.fc_publish_version.join(',');
            } else {
                // 单个版本，直接使用
                params.fc_publish_version = state.queryData.fc_publish_version;
            }
        }
        
        // 添加任务类型筛选参数
        if (state.queryData.task_type) {
            params.task_type = state.queryData.task_type;
        }
        
        // 添加任务预计开始时间范围筛选参数
        if (state.queryData.plan_start_time_start) {
            // 将日期对象转换为YYYY-MM-DD格式字符串
            params.plan_start_time_start = state.queryData.plan_start_time_start.toISOString().split('T')[0];
        }
        if (state.queryData.plan_start_time_end) {
            // 将日期对象转换为YYYY-MM-DD格式字符串
            params.plan_start_time_end = state.queryData.plan_start_time_end.toISOString().split('T')[0];
        }
        
        const response: TObj = await apiGet(apiUrl, params);
        state.tableData = response?.results || [];
        state.total = response?.count || 0;
        
        // 使用后端返回的总工时，而不是自己计算
        state.total_hours = response?.total_hours || 0;
    } catch (error) {
        console.error('Error fetching data:', error);
        ElMessage({
            message: '获取数据失败',
            type: 'error',
        });
    } finally {
        state.loading = false;
    }
};

// 页数改变
const handleSizeChange = (val: number) => {
    state.pageSize = val;
    fetchData(state.currentPage, val);
};

const handleCurrentChange = (val: number) => {
    state.currentPage = val;
    fetchData(val, state.pageSize);
};

// 重置
const handleReset = () => {
    state.queryData = {
        responsible_person: [],
        epic_name: undefined,
        story_name: undefined,
        fc_publish_version: [],
        task_type: undefined,
        plan_start_time_start: undefined,
        plan_start_time_end: undefined,
    };
    fetchData();
};

// 查询
const handleSearch = () => {
    state.currentPage = 1;
    fetchData(1, state.pageSize);
};

// 初始化数据
fetchResponsiblePersons();
fetchPublishVersions();
fetchTaskTypes();
fetchData();
</script>

<template>
  <div class="human-resource-statistics">
    <!-- 搜索区域 -->
    <div class="search-area">
      <div class="search-inner">
        <el-select 
          v-model="state.queryData.responsible_person" 
          placeholder="责任人" 
          class="width200" 
          multiple
          clearable 
          filterable
          collapse-tags
          collapse-tags-tooltip
          :filter-method="filterResponsiblePerson">
          <el-option v-for="person in filteredResponsiblePersonOptions" :key="person" :label="person" :value="person" />
        </el-select>
        
        <el-input
          v-model="state.queryData.epic_name"
          placeholder="史诗"
          class="width200"
          clearable
        />
        
        <el-input
          v-model="state.queryData.story_name"
          placeholder="故事"
          class="width200"
          clearable
        />
        
        <el-select
          v-model="state.queryData.fc_publish_version"
          placeholder="版本"
          class="width200"
          multiple
          clearable
          filterable
          collapse-tags
          collapse-tags-tooltip
          :filter-method="filterPublishVersion"
        >
          <el-option v-for="version in filteredPublishVersionOptions" :key="version" :label="version" :value="version" />
        </el-select>
        
        <el-select
          v-model="state.queryData.task_type"
          placeholder="任务类型"
          class="width200"
          clearable
        >
          <el-option v-for="type in taskTypeOptions" :key="type" :label="type" :value="type" />
        </el-select>
        
        <div class="date-range">
          <span class="date-label">任务预计开始时间：</span>
          <el-date-picker
            v-model="state.queryData.plan_start_time_start"
            type="date"
            placeholder="开始日期"
            class="width150"
            clearable
          />
          <span class="date-separator">至</span>
          <el-date-picker
            v-model="state.queryData.plan_start_time_end"
            type="date"
            placeholder="结束日期"
            class="width150"
            clearable
          />
        </div>
        
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="statistics-info">
      <el-card>
        <div class="info-item">
          <span class="label">总责任人数量：</span>
          <span class="value">{{ state.total }}</span>
        </div>
        <div class="info-item">
          <span class="label">总工时：</span>
          <span class="value">{{ state.total_hours }}</span>
        </div>
      </el-card>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table 
        :data="state.tableData" 
        border 
        style="width: 100%;" 
        v-loading="state.loading">
        <el-table-column prop="responsible_person" label="责任人" width="200" />
        <el-table-column prop="task_count" label="任务数" width="150" align="center" />
        <el-table-column prop="total_hours" label="总工时" width="150" align="center" />
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-area">
        <span class="total-count">共 {{ state.total }} 条记录</span>
        <el-pagination 
          v-model:currentPage="state.currentPage" 
          v-model:page-size="state.pageSize"
          :page-sizes="[10, 20, 50, 100]" 
          size="small" 
          layout="sizes, prev, pager, next, jumper" 
          :total="state.total" 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<style scoped>
.human-resource-statistics {
  padding: 20px;
}

.search-area {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-inner {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.width200 {
  width: 200px;
}

.width150 {
  width: 150px;
}

.date-range {
  display: flex;
  align-items: center;
  gap: 10px;
}

.date-label {
  font-weight: bold;
  color: #606266;
}

.date-separator {
  color: #909399;
}

.statistics-info {
  margin-bottom: 20px;
}

.info-item {
  display: inline-block;
  margin-right: 30px;
}

.label {
  font-weight: bold;
  margin-right: 5px;
}

.value {
  font-size: 18px;
  color: #409eff;
}

.table-area {
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
}

.pagination-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 10px 0;
}

.total-count {
  color: #606266;
  font-size: 14px;
}
</style>